public StringJoiner(CharSequence delimiter)
NullPointerException Exception Thrown if the delimiter is null
public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
NullPointerException Exception Thrown if prefix, delimiter, or suffix is null.
Method | Action Performed |
---|---|
add() | Adds a duplicate of the specified CharSequence value as the StringJoiner value's subsequent element. In that case, "null" is added if newElement is null. |
length() | This StringJoiner's String representation's length is returned. |
merge() | Adds the given StringJoiner's contents, without a prefix or a suffix, as the following element if it is not empty. The call has no impact if the provided StringJoiner is empty. Let's say that the other StringJoiner employs a different delimiter. In that case, the result is appended to this StringJoiner as a single element by concatenating the elements from the other StringJoiner with that delimiter. |
toString() | it returns the String object for this StringJoiner. |
setEmptyValue() | sets the string that will be used to determine the string representation of this StringJoiner when no elements have been added yet, or when it is empty. |
import java.util.StringJoiner; public class Main { public static void main(String[] args) { // Creating a StringJoiner object with delimiter "," StringJoiner sj1 = new StringJoiner(","); // Using setEmptyValue() method to set default value for empty StringJoiner object sj1.setEmptyValue("sj1 is empty"); System.out.println(sj1); // sj1 is empty // Using add() method to add elements to StringJoiner object sj1.add("Ram").add("Jyoti").add("Alice").add("Shyam"); System.out.println(sj1); // Ram,Jyoti,Alice,Shyam // Using length() method to get length of the StringJoiner object System.out.println("Length of sj1 : " + sj1.length()); // Length of sj1 : 17 // Creating a new StringJoiner object with delimiter ":" StringJoiner sj2 = new StringJoiner(":"); sj2.add("John").add("Jani").add("Jimmy"); // Using merge() method to merge two StringJoiner objects sj1.merge(sj2); // Using toString() method to get the String representation of the StringJoiner object System.out.println(sj1.toString()); // Ram,Jyoti,Alice,Shyam,John:Jani:Jimmy // Using length() method to get length of the new StringJoiner object after merging System.out.println("Length of new sj1 : " + sj1.length()); // Length of new sj1 : 26 } }
This program creates two StringJoiner objects, adds elements to them using the add() method, sets a default value for the first object using setEmptyValue(), merges the two objects using the merge() method, and finally, gets the String representation of the merged object using the toString() method and gets its length using the length() method.
Output:
sj1 is empty
Ram,Shyam,Alice,Bob
Length of sj1 : 17
Ram,Shyam,Alice,Bob,John:Jane:Jim
Length of new sj1 : 26
Post your comment